﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Net_SCADA
{
    public class Item
    {
        public string Add { get; set; } = "";
        public int ID { get; set; } = 0;
        public string DataType { get; set; } = "";
        public int DP { get; set; } = 0;
        public float Min { get; set; } = 0;
        public float Max { get; set; } = 1000;
        public bool isShow { get; set; } = true;
        public bool isRecord { get; set; } = true;
        public double ItemValue { get; private set; } = 0;
        public StringBuilder VisibleValue { get; private set; } = new StringBuilder();

        public object[] GetPLCSetValue(object sv)
        {
            if (DataType.ToUpper() == "TIME")
            {
                string s=  sv.ToString();
                if (s.Length == 0) return new object[] { 0 , 0 };
                int idot=s.IndexOf(".");
                if (idot == -1) return new object[] {Convert.ToInt32(s),0 };
                if (idot == 0) return new object[] {0,Convert.ToInt32(s.Substring(1))};
                if(idot==s.Length-1) return new object[] { Convert.ToInt32(s.Substring(0 , idot)) , 0 };
                return new object[] {Convert.ToInt32(s.Substring(0,idot)),Convert.ToInt32(s.Substring(idot+1)) };
            }
            if(DataType.ToUpper()=="BIN" || DataType.ToUpper() == "INT")
                return new object[] { Convert.ToInt32(sv) };
            return new object[] {Convert.ToSingle( sv) };
        }
        public void SetItemValue(object[] v)
        {
            if (v == null || v.Length == 0)
            {
                VisibleValue = new StringBuilder("-");
                ItemValue = 0;
                return;
            }
            try
            {
                if (DataType.ToUpper() == "TIME")
                {
                    if (v.Length >= 2)
                    {
                        VisibleValue = new StringBuilder().Append(v[0]).Append( ".").Append(v[1]);
                        ItemValue = Convert.ToInt32(v[0]) * 60 + Convert.ToInt32(v[1]);
                        return;
                    }
                }
                VisibleValue = new StringBuilder().Append(v[0]);
                if (DataType.ToUpper() == "REAL")
                {
                    ItemValue =Math.Round( Convert.ToSingle(v[0]),3);
                    return;
                }
                ItemValue = Convert.ToInt32(v[0]);
            }
            catch (Exception)
            {
                VisibleValue = new StringBuilder("-");
                ItemValue = 0;
            }
        }
    }
}